<template>
  <div class="app-container">
    <div v-if="isShowSearchBtn" class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="菜单名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select
            v-model="queryParams.type"
            placeholder="全部"
            clearable
            class="!w-[120px]"
          >
            <el-option
              v-for="item in calendarTypeOptions"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="is_hid">
          <el-select
            v-model="queryParams.is_hid"
            placeholder="全部"
            clearable
            class="!w-[100px]"
          >
            <el-option label="启用" value="0" />
            <el-option label="禁用" value="1" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery">
            <i-ep-refresh />
            重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <div class="flex justify-between">
          <div>
            <el-button
              v-hasPerm="['permission@add']"
              type="success"
              @click="openDialog()"
              ><i-ep-plus />新增</el-button
            >
            <el-button
              v-hasPerm="['permission@del']"
              type="danger"
              v-if="removeIds.length > 0"
              @click="handleDelete()"
              ><i-ep-delete />删除</el-button
            >
          </div>
          <div>
            <el-button
              class="ml-3"
              title="展开/折叠"
              @click="expandTable"
              icon="Sort"
              circle
            />
            <el-button
              class="ml-3"
              @click="handleSearchShowBtn"
              icon="Search"
              circle
            />
            <el-button
              class="ml-3"
              title="刷新"
              @click="handleQuery"
              icon="Refresh"
              circle
            />
          </div>
        </div>
      </template>
      <el-table
        v-loading="loading"
        :data="pageData"
        fit
        row-key="id"
        show-header
        :default-expand-all="tableExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column label="菜单名称" align="left">
          <template #default="scope">
            <span class="link-type" @click="openDialog(scope.row.id)">{{
              scope.row.permission_name
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="图标" align="center">
          <template #default="scope">
            <el-icon
              v-if="scope.row.icon && scope.row.icon.startsWith('el-icon')"
              class="sub-el-icon"
            >
              <component :is="scope.row.icon.replace('el-icon-', '')" />
            </el-icon>
            <svg-icon v-if="scope.row.icon" :icon-class="scope.row.icon" />
          </template>
        </el-table-column>
        <el-table-column label="路由Path" align="left">
          <template #default="scope">
            <span>{{ scope.row.route }}</span>
          </template>
        </el-table-column>
        <el-table-column label="权限标识" align="left">
          <template #default="scope">
            <span>{{ scope.row.permission_mark }}</span>
          </template>
        </el-table-column>
        <el-table-column label="类型" align="left">
          <template #default="scope">
            <el-tag v-if="scope.row.type === 1" type="primary" effect="dark">
              导航菜单
            </el-tag>
            <el-tag v-if="scope.row.type === 2" type="success" effect="dark">
              按钮菜单
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center">
          <template #default="scope">
            <span>{{ scope.row.sort }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" class-name="status-col">
          <template #default="scope">
            <el-tag
              effect="dark"
              :type="scope.row.hidden == 0 ? 'success' : 'danger'"
              >{{ scope.row.hidden == 0 ? "显示" : "隐藏" }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="160">
          <template #default="scope">
            <span>{{ scope.row.created_at }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="130"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              v-hasPerm="['permission@edit']"
              title="编辑"
              type="primary"
              icon="edit"
              circle
              @click="openDialog(scope.row.id)"
            />
            <el-button
              v-hasPerm="['permission@del']"
              title="删除"
              icon="delete"
              circle
              type="danger"
              @click="handleDelete(scope.row.id)"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-position="right"
        label-width="auto"
        :inline="true"
      >
        <el-form-item label="父级菜单" prop="parent_id">
          <el-cascader
            v-model="formData.parent_id"
            :options="cascaderData"
            :props="{ checkStrictly: true }"
            @change="cascaderCheck"
            clearable
          />
        </el-form-item>
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="formData.type" @change="typeChange">
            <el-radio-button label="菜单" value="1" />
            <el-radio-button label="按钮" value="2" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单名称" prop="permission_name">
          <el-input
            v-model="formData.permission_name"
            placeholder="请输入2-100字符的菜单名称"
          />
        </el-form-item>
        <el-form-item label="权限标识" prop="permission_mark">
          <el-input
            v-model="formData.permission_mark"
            placeholder="请输入2-120字符的权限标识"
          />
        </el-form-item>
        <el-form-item label="模块" prop="module" v-if="isShowForm">
          <el-input v-model="formData.module" placeholder="请输入模块名称" />
        </el-form-item>
        <el-form-item label="菜单图标" prop="icon" v-if="isShowForm">
          <el-input v-model="formData.icon" placeholder="请输入菜单图标" />
        </el-form-item>
        <el-form-item label="菜单Path" prop="route" v-if="isShowForm">
          <el-input v-model="formData.route" placeholder="请输入菜单Path" />
        </el-form-item>
        <el-form-item label="Redirect" prop="redirect" v-if="isShowForm">
          <el-input v-model="formData.redirect" placeholder="请输入Redirect" />
        </el-form-item>
        <el-form-item label="Keepalive">
          <el-radio-group prop="keepalive" v-model="formData.keepalive">
            <el-radio :value="1">开启</el-radio>
            <el-radio :value="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="Hidden">
          <el-radio-group prop="hidden" v-model="formData.hidden">
            <el-radio :value="0">显示</el-radio>
            <el-radio :value="1">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  createPermission,
  delPermission,
  getAll,
  getData,
  getMenuForm,
  updatePermission,
} from "@/api/menu";
import { MenuQuery, MenusForm, MenuVO } from "@/api/menu/types";

const loading = ref(false); //  加载状态
const isShowForm = ref(true);
const cascaderData = ref([]);
const tableExpandAll = ref(false);
const queryParams = reactive<MenuQuery>({
  p: 1,
  limit: 10,
});
const queryFormRef = ref(ElForm); // 查询表单
const userFormRef = ref(ElForm); // 用户表单
const pageData = ref<MenuVO[]>(); // 用户分页数据
const isShowSearchBtn = ref(false);
const removeIds = ref([]); // 删除用户ID集合 用于批量删除

const calendarTypeOptions = ref([
  { value: "1", label: "导航菜单" },
  { value: "2", label: "按钮菜单" },
]);
// 用户表单数据
const formData = reactive<MenusForm>({
  hidden: 0,
  keepalive: 1,
  parent_id: 0,
  sort: 0,
});

const rules = reactive({
  title: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  type: [{ required: true, message: "类型不能为空", trigger: "blur" }],
});

function handleQuery() {
  loading.value = true;
  getData(queryParams)
    .then(({ data }) => {
      pageData.value = data;
    })
    .finally(() => {
      loading.value = false;
    });
}
//获取所有数据
function getMenuAll() {
  getAll().then(({ data }) => {
    cascaderData.value = data;
  });
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  userFormRef.value.validate((valid: any) => {
    if (valid) {
      const ids = formData.id;
      loading.value = true;
      if (ids) {
        updatePermission(formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        createPermission(formData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 3000);

// 弹窗对象
const dialog = reactive({
  visible: false,
  width: 800,
  title: "",
});

/**
 * 打开弹窗
 *
 * @param id 用户ID
 */
async function openDialog(id?: number) {
  dialog.visible = true;
  // 用户表单弹窗
  // await loadRoleOptions();
  if (id) {
    dialog.title = "修改";
    getMenuForm(id).then(({ data }) => {
      isShowForm.value = data.type == 1;
      Object.assign(formData, { ...data });
    });
  } else {
    dialog.title = "新增";
  }
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
  formData.id = undefined;
  formData.hidden = 0;
  formData.sort = 0;
  handleQuery();
}

//删除
function handleDelete(id?: number) {
  const ids = id || removeIds.value;
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    delPermission({ ids: ids }).then(() => {
      handleQuery();
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

//重置查询表单
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
  isShowForm.value = true;
}

function typeChange(params: any) {
  isShowForm.value = params == 1;
}

//收起展开搜索按钮
function handleSearchShowBtn() {
  isShowSearchBtn.value = isShowSearchBtn.value === false;
}

function cascaderCheck(data: any) {
  if (data.length > 0) {
    formData.parent_id = data[data.length - 1];
  } else {
    formData.parent_id = 0;
  }
}

function expandTable() {
  tableExpandAll.value = tableExpandAll.value === false;
  console.log(tableExpandAll.value);
}

onMounted(() => {
  handleQuery();
  getMenuAll();
});
</script>

<style></style>
